//
//  AppDelegate.m
//  TengyunStation
//
//  Created by Johnny on 15/8/21.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "AppDelegate.h"
#import "HomeViewController.h"
#import "LoginViewController.h"
#import "Singleton.h"
#import "TSHeader.h"
#import "UIImage+UIColor.h"
#import "SocketRequest.h"
#import "VersionAlertView.h"
#import "ReceiverDBModel.h"
#import "ExpresserDBModel.h"
#import "ComMethod.h"
#import "PositionDBModel.h"
#import "MobClick.h"

@interface AppDelegate ()<SocketRequestDelegate,VersionAlertViewDelegate> {
    SocketRequest *_socketRequest;
    HomeViewController *_homeVC;
}

@end

@implementation AppDelegate

- (void)setUmengTrack {
#ifdef DEBUG
    [MobClick setLogEnabled:YES];
#endif
    [MobClick setAppVersion:XcodeAppVersion];
    [MobClick startWithAppkey:UmengAppKey reportPolicy:REALTIME channelId:@"TengyunBao"];
    [MobClick updateOnlineConfig];
    [MobClick setEncryptEnabled:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onlineConfigCallBack:) name:UMOnlineConfigDidFinishedNotification object:nil];
}

- (void)onlineConfigCallBack:(NSNotification *)note {
    DLog(@"online config has fininshed and note = %@", note.userInfo);
}

//添加通知notification
- (void)addNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessNotification) name:@"LoginSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoutSuccessNotification) name:@"LogoutSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(freePositionNotification:) name:@"positionfreenotification" object:nil];
}
- (void)loginSuccessNotification {
    [self messageSocket];
    _homeVC = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
    UINavigationController *homeNC = [[UINavigationController alloc] initWithRootViewController:_homeVC];
    self.window.rootViewController = homeNC;
}
- (void)logoutSuccessNotification {
    //退出登录——清空数据
    [[Singleton shareInstance].userMessage deleteObject];
    [Singleton shareInstance].userMessage = nil;
    [Singleton shareInstance].version = nil;
    [Singleton shareInstance].statisticsCount = nil;
    [ComMethod clearJKDBModelData];
    [_homeVC stopTimer];
    _homeVC = nil;
    LoginViewController *loginVC = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
    UINavigationController *loginNC = [[UINavigationController alloc] initWithRootViewController:loginVC];
    self.window.rootViewController = loginNC;
}
//释放库位号同时通知后台改批次已经接收完成了
- (void)freePositionNotification:(NSNotification *)notification {
    NSString *batchNo = [notification.userInfo objectForKey:@"batchNo"];
    int expressType = [[notification.userInfo objectForKey:@"expressType"] intValue];
    NSString *expresserId = [notification.userInfo objectForKey:@"expresserId"];
    BOOL isSms = [[notification.userInfo objectForKey:@"isSms"] boolValue];
    DLog(@"通知接收完成：%@,%d,%d",batchNo,expressType,isSms);
    if (isSms) {
        NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STSE"]];
        [mutableData appendBytes:[SocketMethod checkLegal:@"2"] length:1];
        [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
        [mutableData appendBytes:[SocketMethod checkLegal:batchNo] length:64];
        NSString *typeString = [NSString stringWithFormat:@"%d",expressType];
        [mutableData appendBytes:[SocketMethod checkLegal:typeString] length:1];
        [mutableData appendBytes:[SocketMethod checkLegal:expresserId] length:64];
        NSData *lengthData = [SocketMethod hexDataWithLength:0];
        [mutableData appendData:lengthData];
        [_socketRequest addSocketData:mutableData SocketTag:6];
    }
    NSString *sql = [NSString stringWithFormat:@"WHERE websiteId = '%@'",[Singleton shareInstance].userMessage.websiteId];
    NSArray *array = [PositionDBModel findByCriteria:sql];
    if (array.count > 0) {
        NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STS3"]];
        [mutableData appendBytes:[@"0" UTF8String] length:1];
        [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
        NSMutableString *mutableString = [[NSMutableString alloc] init];
        for (PositionDBModel *position in array) {
            [mutableString appendString:position.positionNumber];
            [mutableString appendString:@"|"];
        }
        DLog(@"库位号：%@",mutableString);
        NSData *stringData = [mutableString dataUsingEncoding:NSUTF8StringEncoding];
        NSData *lengthData = [SocketMethod hexDataWithLength:stringData.length];
        [mutableData appendData:lengthData];
        [mutableData appendData:stringData];
        [_socketRequest addSocketData:mutableData SocketTag:5];
    }
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    BOOL isFirst = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isfirstused"] boolValue];
    if (!isFirst) {
        [Usermessage clearTable];
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"isfirstused"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    [self setUmengTrack];
    [self addNotification];
    _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    if ([Singleton shareInstance].userMessage) {
        [self getUserMessage];
        _homeVC = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
        UINavigationController *homeNC = [[UINavigationController alloc] initWithRootViewController:_homeVC];
        self.window.rootViewController = homeNC;
    } else {
        LoginViewController *loginVC = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        UINavigationController *loginNC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        self.window.rootViewController = loginNC;
    }
    [self setNavigationBarStyle];
    [self.window makeKeyAndVisible];
    return YES;
}

//设置导航条字体颜色，大小，阴影颜色
- (void)setNavigationBarStyle {
    [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:MainTextColor,NSForegroundColorAttributeName,[UIFont systemFontOfSize:18],NSFontAttributeName, nil]];
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageWithColor:NavigationColor size:CGSizeMake(320, 64)] forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setShadowImage:[UIImage imageWithColor:UIColorFromRGB(0xcdcdcd) size:CGSizeMake(320, 0.5)]];
}
//每次打开应用进入首页时获取用户信息
- (void)getUserMessage {
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STU8"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.userId] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}
- (void)messageSocket {
    [self checkVersion];
    [self getWebsiteMessageSocket];
    NSString *sql = [NSString stringWithFormat:@"WHERE websiteId = '%@'",[Singleton shareInstance].userMessage.websiteId];
    NSArray *array = [ExpresserDBModel findByCriteria:sql];
    if (array.count <= 0) {
        [self getExpresserSocket];
    }
}
//检测版本更新
- (void)checkVersion {
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STO2"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[@"STApp" UTF8String] length:64];
    [mutableData appendBytes:[[SocketMethod getSocketVersion] UTF8String] length:16];
    [_socketRequest addSocketData:mutableData SocketTag:2];
}
//获取站点信息
- (void)getWebsiteMessageSocket {
    if ([Singleton shareInstance].userMessage.websiteId.length > 0) {
        NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STO5"]];
        [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
        NSString *string = [[NSUserDefaults standardUserDefaults] objectForKey:[Singleton shareInstance].userMessage.websiteId];
        DLog(@"上次站点更新时间：:%@",string);
        [mutableData appendBytes:[SocketMethod checkLegal:string] length:32];
        [_socketRequest addSocketData:mutableData SocketTag:3];
    }
}
//获取快递员身份
- (void)getExpresserSocket {
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STO6"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:4];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    if (socket.socketTag == 1) {
        if ([code isEqualToString:SuccessSocket]) {
            Usermessage *userMessage = [[Usermessage alloc] initWithData:data Telephone:[Singleton shareInstance].userMessage.telephone];
            DLog(@"pwdTime:%@",userMessage.pwdUpdateTime);
            DLog(@"pwdTime:%@",[Singleton shareInstance].userMessage.pwdUpdateTime);
            if ([[Singleton shareInstance].userMessage.pwdUpdateTime isEqualToString:userMessage.pwdUpdateTime]) {
                [Singleton shareInstance].userMessage = userMessage;
                [userMessage usermessageSaveOrUpdate];
                //用户信息比对成功后开始请求
                [self messageSocket];
            } else {
                [self logoutSuccessNotification];
            }
        } else {
            [self logoutSuccessNotification];
        }
    } else if (socket.socketTag == 2) {
        if ([code isEqualToString:SuccessSocket]) {
            Version *version = [[Version alloc] initWithData:data];
            [Singleton shareInstance].version = version;
            if (version.isHadNewVersion) {
                if (version.isForce) {
                    VersionAlertView *alert = [[VersionAlertView alloc] initWithTitle:@"版本更新" message:version.updateLog delegate:self cancelButtonTitle:nil sureButtonTitle:@"立即更新"];
                    [alert show];
                } else {
                    VersionAlertView *alert = [[VersionAlertView alloc] initWithTitle:@"版本更新" message:version.updateLog delegate:self cancelButtonTitle:@"取消" sureButtonTitle:@"立即更新"];
                    [alert show];
                }
            }
        }
    } else if (socket.socketTag == 3) {
        if ([code isEqualToString:SuccessSocket]) {
            NSString *updateTime = [SocketMethod stringSubdata:data Range:NSMakeRange(0, 32)];
            [[NSUserDefaults standardUserDefaults] setObject:updateTime forKey:[Singleton shareInstance].userMessage.websiteId];
            NSString *content = [SocketMethod stringDecryHexData:data Range:NSMakeRange(32, data.length - 32)];
            DLog(@"站点用户信息：%@",content);
            NSArray *array = [content componentsSeparatedByString:@"|"];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                for (NSString *string in array) {
                    if (string.length > 0) {
                        ReceiverDBModel *model = [[ReceiverDBModel alloc] initWithString:string];
                        [model saveReceiverDBModel];
                    }
                }
            });
        }
    } else if (socket.socketTag == 4) {
        if ([code isEqualToString:SuccessSocket]) {
            NSString *content = [SocketMethod stringDecryHexData:data];
            DLog(@"站点快递员：%@",content);
            NSArray *array = [content componentsSeparatedByString:@"|"];
            for (NSString *string in array) {
                if (string.length > 0) {
                    ExpresserDBModel *expresser = [[ExpresserDBModel alloc] initWithString:string];
                    [expresser saveExpresserDBModel];
                }
            }
        }
    } else if (socket.socketTag == 5) {
        if ([code isEqualToString:SuccessSocket]) {
            DLog(@"库位号释放成功");
            NSString *sql = [NSString stringWithFormat:@"WHERE websiteId = '%@'",[Singleton shareInstance].userMessage.websiteId];
            [PositionDBModel deleteObjectsByCriteria:sql];
        }
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    
}

#pragma mark CustomAlertViewDelegate
- (void)versionAlertView:(VersionAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[Singleton shareInstance].version.downloadUrl]];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    //删除网页缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
